package com.ethannhu.todaynews.component.api

import com.chuckerteam.chucker.api.ChuckerInterceptor
import com.ethannhu.todaynews.AppContext
import com.ethannhu.todaynews.config.Config
import com.ethannhu.todaynews.util.JSONUtil
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 * 网络相关依赖提供类
 *
 * 列如：OkHttp, Retrofit依赖
 */
object NetWorkModule {



    /**
     * 提供 OkHttpClient
     */
    fun provideOkHttpClient(): OkHttpClient {
        //信任所有证书
        val trustAllCerts = arrayOf<TrustManager>(
            object : X509TrustManager {
                override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
                override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
                override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
            }
        )

        val sslContext: SSLContext = SSLContext.getInstance("SSL")
        sslContext.init(null, trustAllCerts, SecureRandom())
        // 初始化 okhttp
        // 设置绕过证书的配置
        val okHttpClientBuilder = OkHttpClient.Builder()
            .sslSocketFactory(sslContext.socketFactory, trustAllCerts[0] as X509TrustManager)
            .hostnameVerifier { _, _ -> true }

        //配置缓存
        val cache = Cache(AppContext.instance.cacheDir, Config.NETWORK_CACHE_SIZE)
        okHttpClientBuilder.cache(cache)

        okHttpClientBuilder.connectTimeout(10, TimeUnit.SECONDS) //连接超时时间
            .writeTimeout(10, TimeUnit.SECONDS) //写，也就是将数据发送到服务端超时时间
            .readTimeout(10, TimeUnit.SECONDS) //读，将服务端的数据下载到本地

        //添加公共网络请求拦截器
        okHttpClientBuilder.addInterceptor(TokenInterceptor())

        if (Config.DEBUG) {
            //调试模式

            //创建 okhttp 日志拦截器
            val loggingInterceptor = HttpLoggingInterceptor()

            //设置日志等级
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

            //添加到网络框架中
            okHttpClientBuilder.addInterceptor(loggingInterceptor)

            //添加 chucker 实现应用内显示网络请求信息拦截器
            okHttpClientBuilder.addInterceptor(ChuckerInterceptor.Builder(AppContext.instance).build())

        }

        return okHttpClientBuilder.build()
    }

    /**
     * 提供 Retrofit实例
     */
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .client(okHttpClient) //让 Retrofit 使用 okhttp 的 client,可以自定义超时时间，缓存等，如果不设置就使用默认的。
            .baseUrl(Config.ENDPOINT) //api地址
            .addConverterFactory(GsonConverterFactory.create(JSONUtil.createGson())) //使用自定义 gson 配置解析 json
            .build()
    }
}